<?php
namespace App\Admin\Fields;

use Encore\Admin\Form\Field;
use Encore\Admin\Form\Field\Select;
use Encore\Admin\Form\Field\MultipleSelect;

class OrganizationStation extends MultipleSelect
{
    protected $view = 'organization_station';

    public function render()
    {
        $configs = array_merge([
            'allowClear'  => true,
            'placeholder' => [
                'id'   => '',
                'text' => $this->label,
            ],
        ], $this->config);
        $configs = json_encode($configs);
        $name = $this->formatName($this->column);
        $id = $this->formatId($this->id);
        $className = $this->getElementClassSelector();
        $carbarns = $this->form->model()->carbarns;
        $divideds = [];
        if ($carbarns) {
            foreach ($carbarns as $value) {
                $divideds[$value->id] = $value->pivot->divided;
            }
        }
        $this->addVariables(compact('divideds'));

        $this->script = <<<EOT
const firstRow = $("{$className}").closest(".row").first().clone()
const wrap = $("#{$name}-wrap")
$("{$className}").select2({$configs});

wrap.on("click", ".plus", function (e) {
    let newRow = firstRow.clone()
    newRow.find("input").val("")
    newRow.find("select").val("")
    let currentRow = $(this).closest(".row")
    currentRow.after(newRow)
    newRow.find("{$className}").select2({$configs})
})
wrap.on("click", ".minus", function (e) {
    if (wrap.find(".row").length <= 1) {
        alert("至少保留一项");
        return
    }
    let currentRow = $(this).closest(".row")
    currentRow.remove()
})
EOT;
        return parent::render();
    }
}